const express = require('express');
const router = express.Router();
const passport = require("passport");

const Profile = require("../../models/Profiles");

// 请求数据 public
router.get("/test", (req, res) => {
  res.json({msg: "profiles"});
});

// 添加 add  private
router.post("/add", passport.authenticate("jwt", {session:false}), (req, res) => {
  const profileFields = {};

  if(req.body.type || req.body.describe || req.body.income || req.body.expend || req.body.cash || req.body.remark){
    profileFields.type = req.body.type,
    profileFields.describe = req.body.describe,
    profileFields.income = req.body.income,
    profileFields.expend = req.body.expend,
    profileFields.cash = req.body.cash,
    profileFields.remark = req.body.remark
  }
  new Profile(profileFields).save.then(profile => {
    res.json(profile);
  })
});

  // 获取单条信息
router.get("/:id", passport.authenticate("jwt", {session:false}), (req, res) => {
    Profile.find({_id:req.params.id})
    .then(profile => {
      if(!profile){
        return res.statue(404).json("尚未添加信息！");
      }
      res.json(profile);
    })
    .catch(err => res.status(404).json(err));
});

// 编辑 edit  private
router.post("/edit/:id", passport.authenticate("jwt", {session:false}), (req, res) => {
  const profileFields = {};

  if(req.body.type || req.body.describe || req.body.income || req.body.expend || req.body.cash || req.body.remark){
    profileFields.type = req.body.type,
    profileFields.describe = req.body.describe,
    profileFields.income = req.body.income,
    profileFields.expend = req.body.expend,
    profileFields.cash = req.body.cash,
    profileFields.remark = req.body.remark
  }
  Profile.findOneAndUpdate(
    {_id: req.params.id},
    //更新内容
    {$set: profileFields},
    {new: true}
  ).then(profile => res.json(profile));
});

//删除

router.delete("/delete/:id", passport.authenticate("jwt", {session:false}), (req, res) => {
  Profile.findOneAndRemove({_id: req.params.id})
    .then(profile => res.json(profile))
    .catch(err => res.status(404).json("删除失败！"));
   
});












module.exports = router;